#!/bin/bash

# shellcheck source=meta-facebook/meta-harma/recipes-phosphor/gpio/phosphor-gpio-monitor/logging-util
source /usr/libexec/phosphor-gpio-monitor/logging-util

HELP="
Usage: smc-event-logger <event> <id_gpio-name>
<event> is the power rail event to log,
e.g. assert / deassert.

<id_gpio-name> is defined in json file,
e.g. 5_health-mmc
"

# get assert or deassert message
if [ "$1" == "assert" ]; then
  action="SMCFailed"
elif [ "$1" == "deassert" ]; then
  action="SMCRestored"
fi

# get gpio chip ID
MESSAGE=$2
number="${MESSAGE%%_*}"

# remove prefix from 0_xxxxxx to xxxxxx
GPIO_NAME="${MESSAGE#*_}"

MSG_ID="xyz.openbmc_project.State.SMC.$action"
DEVICE_PATH="/xyz/openbmc_project/inventory/system/board/Minerva_Aegis/smc0"
STASH_FILE="/run/$GPIO_NAME.log_entry"

if gpio_logging_valid "$number" "$1" ; then
    case $1 in
        "-h")
            echo "$HELP"
            ;;

        "assert")
            if [ ! -s "$STASH_FILE" ]; then
                 /usr/bin/log-create "$MSG_ID" --json \
                     "{ \"IDENTIFIER\": \"${DEVICE_PATH}\", \"FAILURE_TYPE\": \"${GPIO_NAME}\"}" \
                     > "${STASH_FILE}"
            fi
            ;;

        "deassert")
            if [ -s "${STASH_FILE}" ]; then
                log-resolve -p "$(< "${STASH_FILE}")"
                rm "${STASH_FILE}"
            fi
            /usr/bin/log-create "$MSG_ID" --json \
                "{ \"IDENTIFIER\": \"${DEVICE_PATH}\"}"
            ;;
    esac
fi

exit 0
